package com.edais.actions;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.edais.domain.Scattered;
import com.edais.domain.UserChannelPoint;
import com.edais.service.FinancePlanService;
import com.edais.service.LoanService;
import com.edais.service.UserChannelPointService;
import com.edais.service.WeixinEnjoyService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.DecimalFormatUtil;
import com.edais.util.Message;
import com.lb.sssq.service.DepositService;

@Controller
@RequestMapping("/product")

public class ProductAction  implements Serializable{
	private static final Log logger = LogFactory.getLog(ProductAction.class);

	@Autowired
	private FinancePlanService financeService;

	@Autowired
	private LoanService loanService;
	
	@Autowired
	private UserChannelPointService userChannelPointService;
	
	@Autowired
	private DepositService depositService;
	
	@Autowired
	private WeixinEnjoyService weixinEnjoyService;

	/**
	 * E4000434 获取某一产品系列下的产品列表
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getProductList")
	public void getProductList(HttpServletRequest request, HttpServletResponse response){
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String seriesID = paramsMap.get("seriesID");   //理财产品系列id
		
		if (StringUtils.isBlank(seriesID)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			CommonUtil.responseJson(result, response);
			logger.debug("/product/getProductList 传入参数为空-----seriesID");
			return;
		}
		
		try{
			// 获取所有的产品条数
			String totalNum = financeService.getChildFinancePlanCount(seriesID);
			// 抽取产品
			//组装起始条数
			List<Map<String,Object>> financeList = financeService.getChildFinancePlanList(seriesID);
			
			Map<String, Object> mapResult = new HashMap<String, Object>();
			mapResult.put("totalNum", totalNum);
			mapResult.put("listSize", String.valueOf(financeList.size()));
			mapResult.put("list", financeList);
			
			String result = CommonUtil.setResultStringCn(mapResult, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,"");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			
		}catch(Exception e){
			logger.debug("/product/getProductList-----" + e.getMessage());
			
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(),
								Consts.ERROR_CODE, Consts.ErrorMsg.MSG00001,
								Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}
		return;
	}
	
	
	/**
	 * 获取 活期+定期  排序后的产品标的列表
	 * 活期  定期6月 3月  1月
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getProductLoanList")
	public void getProductLoanList(HttpServletRequest request, HttpServletResponse response){
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");// 用户id
		String isAdjustRate = "N";
		BigDecimal adjustRate = BigDecimal.ZERO;
		BigDecimal cusAdjustRate = BigDecimal.ZERO;
		
		try{
			List<Scattered> scatteredList = loanService.queryWxAndAppLoan();
			String periodShowName=loanService.queryBitShowNamePeriod();
			String currentShowName=loanService.queryBitShowNameCurrent();
			/**
			 * 剩余金额小于起头金额，返回100%
			 * 当产品已经超过下架时间，返回100%
			 */
			List<Map<String,Object>> resultListMap = new ArrayList();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (scatteredList != null && scatteredList.size() > 0) {
				
				//获取用户渠道等级积分数据
				UserChannelPoint userChannelPoint = null;
				if (StringUtils.isNotBlank(userId)) {
					Map<String,Object> parm = new HashMap<String, Object>();
					parm.put("userId", userId);
					userChannelPoint = userChannelPointService.findChannelPointByParm(parm);
				}
				//获取活期利率
				Map<String, Object> resMap = depositService.findCurrentRate(userId);
				cusAdjustRate = new BigDecimal(resMap.get("adjustRate").toString());
				
				for(int i =0;i<scatteredList.size();i++) {
					Scattered sc = scatteredList.get(i);
					Map<String,Object> scMap = new HashMap<String,Object>();
					// id
					scMap.put("scatteredLoanId", sc.getId());
					// 产品名称
					scMap.put("productName", sc.getProductName());
					// 借款用途
					scMap.put("borrowType", sc.getBorrowType());
					// 年利率
					scMap.put("annualRate", sc.getAnnualRate());
					// 剩余期数
					scMap.put("remanPeriods", sc.getRemanPeriods());
					//ouyy
					//剩余天数
					scMap.put("remanDays", sc.getRemanDays());
					// 显示名字
					if ("1".equals(sc.getSellingType())) {
						if(sc.getRemanPeriods()==12||sc.getRemanDays()==365){
							scMap.put("showName", "超享计划");
						}else{
							//如果剩余天数为0，表示还是在走老的期数上标流程
							if(sc.getRemanDays()==0){
								scMap.put("showName", periodShowName+sc.getRemanPeriods() + "月期");
							}else{
								scMap.put("showName", periodShowName+sc.getRemanDays() + "天");
							}							
						}
					} else {
						scMap.put("showName", currentShowName);
					}
					// 借款总额
					scMap.put("contactAmount", sc.getContactAmount());
					// 上架金额
					scMap.put("saleTotalAmount", sc.getSaleTotalAmount());
					// 起投金额
					scMap.put("investMinAmount", sc.getInvestMinAmount());
					// 投资进度%
					scMap.put("finishedRatio",
							DecimalFormatUtil.getDecimalFormat0(BigDecimal.ONE.compareTo(sc.getFinishedRatio()) > 0
									&& BigDecimal.ZERO.compareTo(sc.getFinishedRatio()) < 0 ? BigDecimal.ONE : sc.getFinishedRatio()));
					// 剩余金额
					scMap.put("remanAmount", sc.getRemanAmount());
					// 每份金额
					scMap.put("perServingAmount", sc.getPerServingAmount());
					// 可否购买(Y/N)
					scMap.put("openSelling", sc.getOpenSelling());
					// 标的ID
					scMap.put("loanId", sc.getBidId());
					// 理财计划ID
					scMap.put("planId", sc.getPlanId());
					// 下架时间
					scMap.put("endSaleTime", sc.getEndSaleTime()==null?"":sdf.format(sc.getEndSaleTime()));
					// 上架时间
					scMap.put("startSellingTime", sc.getStartSellingTime()==null?"":sdf.format(sc.getStartSellingTime()));

					// 是否推荐 1：推荐 0 不推荐
					scMap.put("isRecommend", sc.getIsRecommend());
					// 上架类别：1-散标，2-随存随取
					scMap.put("sellingType", sc.getSellingType());
					
					isAdjustRate = sc.getIsAdjustRate();
					// 是否调整利率
					scMap.put("isAdjustRate", isAdjustRate);
					// 定期的时候
					if ("1".equals(sc.getSellingType())) {
						if (userChannelPoint != null && "Y".equals(isAdjustRate)) {
							adjustRate = sc.getMaxAdjustRate().multiply(
									new BigDecimal(userChannelPoint.getFixFloatRateChannel()));
						}
						// 调整利率
						scMap.put("adjustRate", adjustRate.setScale(1, RoundingMode.DOWN));
					}
					// 活期的时候
					if ("2".equals(sc.getSellingType())) {
						scMap.put("adjustRate", cusAdjustRate);
					}
					
					// 返回时间
					DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	
					int day = 0;
					int hour = 0;
					int min = 0;
					int sec = 0;
					try {
						Date dateTime=sc.getStartSellingTime();   //产品上架时间
						logger.info("[上架时间]====>"+df.format(dateTime));
						logger.info("[当前时间]====>"+df.format(new Date(System.currentTimeMillis())));
						long time1 = System.currentTimeMillis();  //当前时间
						long time2 = dateTime.getTime();          //上架时间
						logger.info("[当前time1]-->"+time1);
						logger.info("[上架time2]-->"+time2);
						long diff = time2 - time1;
						if (diff >= 0) {
							day = (int) (diff / (24 * 60 * 60 * 1000));
							hour = (int) (diff / (60 * 60 * 1000) - day * 24);
							min = (int) ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
							sec = (int) (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);	
						} else {
							day=0;  hour=0;  min=0; sec=0;
						}
					logger.info("[上架时间距离当前时间]-->" + day + "天" + hour + "小时" + min + "分" + sec + "秒");
					} catch (Exception e) {
						e.printStackTrace();
						logger.info("[获取时间发生异常]-->" + e.getMessage());
					}
					scMap.put("day", day);
					scMap.put("hour", hour);
					scMap.put("min", min);
					scMap.put("sec", sec);
					
					resultListMap.add(scMap);
				}
			} else {
				// 处理返回结果
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE, "",
						"未获取产品信息！");
				CommonUtil.responseJson(result, response);
				return;
			}
			Map<String, Object> mapResult = new HashMap<String, Object>();
			mapResult.put("listSize", String.valueOf(resultListMap.size()));
			mapResult.put("list", resultListMap);
			
			String result = CommonUtil.setResultStringCn(mapResult,
					Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("获取散标列表数据发生异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",
				Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	/**
	 * @Description: 网站首页
	 * @param @param request
	 * @param @param response   
	 * @return void  
	 * @throws
	 * @author chenshufeng
	 * @date 2016-9-5
	 */
	@RequestMapping(value = "/getProductLoanListWeb")
	public void getProductLoanListWeb(HttpServletRequest request, HttpServletResponse response){
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String userId = paramsMap.get("userId");// 用户id
		String isAdjustRate = "N";
		BigDecimal adjustRate = BigDecimal.ZERO;
		BigDecimal cusAdjustRate = BigDecimal.ZERO;
		
		try{
			List<Scattered> scatteredList = loanService.queryWxAndAppLoan();
			String periodShowName=loanService.queryBitShowNamePeriod();
			String currentShowName=loanService.queryBitShowNameCurrent();
			/**
			 * 剩余金额小于起头金额，返回100%
			 * 当产品已经超过下架时间，返回100%
			 */
			List<Map<String,Object>> resultListMap = new ArrayList();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (scatteredList != null && scatteredList.size() > 0) {
				
				//获取用户渠道等级积分数据
				UserChannelPoint userChannelPoint = null;
				if (StringUtils.isNotBlank(userId)) {
					Map<String,Object> parm = new HashMap<String, Object>();
					parm.put("userId", userId);
					userChannelPoint = userChannelPointService.findChannelPointByParm(parm);
				}
				//获取活期利率
				Map<String, Object> resMap = depositService.findCurrentRate(userId);
				cusAdjustRate = new BigDecimal(resMap.get("adjustRate").toString());
				
				for(int i =0;i<scatteredList.size();i++) {
					Scattered sc = scatteredList.get(i);
					Map<String,Object> scMap = new HashMap<String,Object>();
					// id
					scMap.put("scatteredLoanId", sc.getId());
					// 产品名称
					scMap.put("productName", sc.getProductName());
					// 借款用途
					scMap.put("borrowType", sc.getBorrowType());
					// 年利率
					scMap.put("annualRate", sc.getAnnualRate());
					// 剩余期数
					scMap.put("remanPeriods", sc.getRemanPeriods());
					//ouyy
					//剩余天数
					scMap.put("remanDays", sc.getRemanDays());
					// 显示名字
					if ("1".equals(sc.getSellingType())) {
						if(sc.getRemanPeriods()==12||sc.getRemanDays()==365){
							scMap.put("showName", "超享计划");
						}else{
							//如果剩余天数为0，表示还是在走老的期数上标流程
							if(sc.getRemanDays()==0){
								scMap.put("showName", periodShowName+sc.getRemanPeriods() + "月期");
							}else{
								scMap.put("showName", periodShowName+sc.getRemanDays() + "天");
							}							
						}
					} else {
						scMap.put("showName", currentShowName);
					}
					// 借款总额
					scMap.put("contactAmount", sc.getContactAmount());
					// 上架金额
					scMap.put("saleTotalAmount", sc.getSaleTotalAmount());
					// 起投金额
					scMap.put("investMinAmount", sc.getInvestMinAmount());
					// 投资进度%
					scMap.put("finishedRatio",
							DecimalFormatUtil.getDecimalFormat0(BigDecimal.ONE.compareTo(sc.getFinishedRatio()) > 0
									&& BigDecimal.ZERO.compareTo(sc.getFinishedRatio()) < 0 ? BigDecimal.ONE : sc.getFinishedRatio()));
					// 剩余金额
					scMap.put("remanAmount", sc.getRemanAmount());
					// 每份金额
					scMap.put("perServingAmount", sc.getPerServingAmount());
					// 可否购买(Y/N)
					scMap.put("openSelling", sc.getOpenSelling());
					// 标的ID
					scMap.put("loanId", sc.getBidId());
					// 理财计划ID
					scMap.put("planId", sc.getPlanId());
					// 下架时间
					scMap.put("endSaleTime", sc.getEndSaleTime()==null?"":sdf.format(sc.getEndSaleTime()));
					// 上架时间
					scMap.put("startSellingTime", sc.getStartSellingTime()==null?"":sdf.format(sc.getStartSellingTime()));
					
					// 是否推荐 1：推荐 0 不推荐
					scMap.put("isRecommend", sc.getIsRecommend());
					// 上架类别：1-散标，2-随存随取
					scMap.put("sellingType", sc.getSellingType());
					
					isAdjustRate = sc.getIsAdjustRate();
					// 是否调整利率
					scMap.put("isAdjustRate", isAdjustRate);
					// 定期的时候
					if ("1".equals(sc.getSellingType())) {
						if (userChannelPoint != null && "Y".equals(isAdjustRate)) {
							adjustRate = sc.getMaxAdjustRate().multiply(
									new BigDecimal(userChannelPoint.getFixFloatRateChannel()));
						}
						// 调整利率
						scMap.put("adjustRate", adjustRate.setScale(1, RoundingMode.DOWN));
					}
					// 活期的时候
					if ("2".equals(sc.getSellingType())) {
						scMap.put("adjustRate", cusAdjustRate);
					}
					
					// 返回时间
					DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	
					int day = 0;
					int hour = 0;
					int min = 0;
					int sec = 0;
					try {
						Date dateTime=sc.getStartSellingTime();   //产品上架时间
						logger.info("[上架时间]====>"+df.format(dateTime));
						logger.info("[当前时间]====>"+df.format(new Date(System.currentTimeMillis())));
						long time1 = System.currentTimeMillis();  //当前时间
						long time2 = dateTime.getTime();          //上架时间
						logger.info("[当前time1]-->"+time1);
						logger.info("[上架time2]-->"+time2);
						long diff = time2 - time1;
						if (diff >= 0) {
							day = (int) (diff / (24 * 60 * 60 * 1000));
							hour = (int) (diff / (60 * 60 * 1000) - day * 24);
							min = (int) ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
							sec = (int) (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);	
						} else {
							day=0;  hour=0;  min=0; sec=0;
						}
						logger.info("[上架时间距离当前时间]-->" + day + "天" + hour + "小时" + min + "分" + sec + "秒");
					} catch (Exception e) {
						e.printStackTrace();
						logger.info("[获取时间发生异常]-->" + e.getMessage());
					}
					scMap.put("day", day);
					scMap.put("hour", hour);
					scMap.put("min", min);
					scMap.put("sec", sec);
					
					resultListMap.add(scMap);
				}
			} else {
				// 处理返回结果
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.CHECK_CODE, "",
						"未获取产品信息！");
				CommonUtil.responseJson(result, response);
				return;
			}
			//add by chenshufeng 2016-9-4
			Map<String, String> map = new HashMap<String, String>();
			map.put("productId", "107");
			Map<String, Object> enjoyPlanMap = weixinEnjoyService.getEnjoyPlanDetail(map);
			Map<String,Object> scMap = new HashMap<String,Object>();
			// id
			scMap.put("scatteredLoanId", "");
			// 产品名称
			scMap.put("productName", enjoyPlanMap.get("productName"));
			// 年利率
			scMap.put("annualRate", enjoyPlanMap.get("returnRate"));
			// 借款用途
			scMap.put("borrowType", "");
			// 剩余期数
			scMap.put("remanPeriods", "");
			//ouyy
			scMap.put("showName", enjoyPlanMap.get("productName"));
			//剩余天数
			scMap.put("remanDays", "");
			// 借款总额
			scMap.put("contactAmount", "");
			// 上架金额
			scMap.put("saleTotalAmount", "");
			// 起投金额
			scMap.put("investMinAmount", enjoyPlanMap.get("investMinAmount"));
			// 投资进度%
			scMap.put("finishedRatio", "");
			// 剩余金额
			scMap.put("remanAmount", "");
			// 每份金额
			scMap.put("perServingAmount", "");
			// 可否购买(Y/N)
			scMap.put("openSelling", enjoyPlanMap.get("isValid"));
			// 标的ID
			scMap.put("loanId", "");
			// 理财计划ID
			scMap.put("planId", enjoyPlanMap.get("sloanId"));
			// 下架时间
			scMap.put("endSaleTime", "");
			// 上架时间
			scMap.put("startSellingTime", "");
			// 是否推荐 1：推荐 0 不推荐
			scMap.put("isRecommend", "");
			// 上架类别：1-散标，2-随存随取
			scMap.put("sellingType", "");
			// 是否调整利率
			scMap.put("isAdjustRate", "");
			scMap.put("adjustRate", "");
			
			// 返回时间
			scMap.put("day", 0);
			scMap.put("hour", 0);
			scMap.put("min", 0);
			scMap.put("sec", 0);
			resultListMap.add(scMap);
			Map<String, Object> mapResult = new HashMap<String, Object>();
			mapResult.put("listSize", String.valueOf(resultListMap.size()));
			mapResult.put("list", resultListMap);
			
			String result = CommonUtil.setResultStringCn(mapResult,
					Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("获取散标列表数据发生异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
					new HashMap<String, Object>(),Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}

}
